﻿using System;
using System.Drawing.Design;
using System.ComponentModel;

namespace UtfprLibrary.Windows.Forms.ComponentModel {
    internal class UtfprRadioButtonEditor : UITypeEditor {

        public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context) {
            AddEventHandler(context.Instance, "SomePropertyChanged");

            return base.GetEditStyle(context);
        }

        private void AddEventHandler(object target, string methodName) {
            var eInfo = target.GetType().GetEvent("PropertyChanged");
            var handler = Delegate.CreateDelegate(
                eInfo.EventHandlerType, this, methodName);
            eInfo.AddEventHandler(target, handler);
        }

        private void SomePropertyChanged(object sender, PropertyChangedEventArgs e) {
            if (e.PropertyName == "Value") {
                if (IsNumeric(sender)) {
                    ValidateProperty(sender);
                }
            } else  if(e.PropertyName == "IsNumeric") {
                if (IsNumeric(sender)) {
                    try {
                        ValidateProperty(sender);
                    } catch (FormatException) {
                        SetText(sender, "1");
                    }
                } else if(!IsNumeric(sender)) {
                    SetText(sender, "Insira um valor");    
                }
            }
        }

        private void ValidateProperty(object sender) {
            try {
                int.Parse(GetText(sender));
            } catch (FormatException) {
                throw new FormatException("Valor inválido, somente valores numéricos são aceitos");
            }
        }

        private bool IsNumeric(object sender) {
            return (bool)sender.GetType()
                .GetProperty("IsNumeric").GetValue(sender, null);
        }

        private string GetText(object sender) {
            return (string)sender.GetType()
                .GetProperty("Value").GetValue(sender, null);
        }

        private void SetText(object sender, string message) {
            sender.GetType().GetProperty("Value")
                .SetValue(sender, message, null);
        }
    }
}
